package com.hingsmy.pma.controllers;

import com.fasterxml.jackson.core.JsonProcessingException;
import com.fasterxml.jackson.databind.ObjectMapper;
import com.hingsmy.pma.dao.ProjectRepository;
import com.hingsmy.pma.dao.StudentRepository;
import com.hingsmy.pma.dao.UserAccountRepository;
import com.hingsmy.pma.dto.ChartData;
import com.hingsmy.pma.dto.StudentProject;
import com.hingsmy.pma.entities.Student;
import com.hingsmy.pma.entities.Project;
import com.hingsmy.pma.entities.UserAccount;

import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.security.core.context.SecurityContextHolder;
import org.springframework.security.core.userdetails.User;
import org.springframework.stereotype.Controller;
import org.springframework.ui.Model;
import org.springframework.web.bind.annotation.GetMapping;

import java.util.List;

@Controller
public class HomeController {

    @Value("${version}")
    private String version;

    @Autowired
    ProjectRepository projectRepository;

    @Autowired
    StudentRepository studentRepository;

    @GetMapping("/")
    public String displayHome(Model model) throws JsonProcessingException {
        model.addAttribute("versionNumber",version);

        List<Project> projects = projectRepository.findAll();
        model.addAttribute("projects", projects);

        List<ChartData> projectStudentData=projectRepository.getProjectStatus();
        ObjectMapper objectMapper=new ObjectMapper();
        String jsonString = objectMapper.writeValueAsString(projectStudentData);
        model.addAttribute("projectStudentData",jsonString);

        List<StudentProject> studentProjects=studentRepository.studentProjects();
        model.addAttribute("studentProjects",studentProjects);


        Object principal = SecurityContextHolder.getContext().getAuthentication().getPrincipal();
        if("anonymousUser".equals(principal)) {
            model.addAttribute("name","未登录");
        }else {
            User user = (User)principal;
            model.addAttribute("name",user.getUsername());
        }
        return "main/home";
    }
}
